import { Popover } from 'antd';
import React, { useState, useEffect } from 'react';
import Speaking from '@/components/Speaking';
import wx from 'weixin-js-sdk';
import { getFetch } from '@/utils/doFetch';
import { useAsyncEffect, useInterval } from 'ahooks';

function Recorder({ socket, companies }) {
  const [isrecord, setIsrecord] = useState(false);
  const [recordState, setRecordState] = useState(null);
  const [time, setTime] = useState(0);

  const clear = useInterval(
    () => {
      setTime((t) => t + 1);
    },
    isrecord ? 1000 : undefined,
    {
      immediate: false,
    },
  );

  useAsyncEffect(async () => {
    let res = await getFetch({
      url: '/wbn-api/wechat/signature',
      params: { url: document.URL },
    });

    if (res.code == 0) {
      wx.config({
        debug: false,
        appId: res.data.app_id,
        timestamp: res.data.timestamp,
        nonceStr: res.data.nonce_str,
        signature: res.data.signature,
        jsApiList: [
          'startRecord',
          'stopRecord',
          'onVoiceRecordEnd',
          'uploadVoice',
          'downloadVoice',
        ], // 需要使用的API列表
      });
      //ready之后
      wx.ready(function () {
        wx.onVoiceRecordEnd({
          complete: function (res) {
            var localId = res.localId;
            // 在此处可处理录音完成后的逻辑
            endaction(localId);
          },
        });
      });
      wx.error(function () {});
    }
  }, []);

  function stopRecord() {
    wx.stopRecord({
      success: function (res) {
        var localId = res.localId;
        endaction(localId);
      },
    });
  }

  function endaction(localId) {
    wx.uploadVoice({
      localId, // 需要上传的音频的本地ID，由stopRecord接口获得
      isShowProgressTips: 1, // 默认为1，显示进度提示
      success: function (res) {
        var serverId = res.serverId; // 返回音频的服务器端ID
        const val = JSON.stringify({
          localId,
          serverId,
        });
        socket.emit(
          'customer-message',
          JSON.stringify({
            company_id: companies?.id,
            message_type: 'audio',
            message_content: val,
          }),
        );
      },
    });
  }

  useEffect(() => {
    if (isrecord === false) {
      setTime(0);
    }
  }, [isrecord]);

  return (
    <div
      style={{ padding: 12, borderRadius: 8, backgroundColor: '#fff' }}
      onTouchStart={(e) => {
        e.preventDefault();
        setIsrecord(true);
        setTimeout(() => {
          wx.startRecord();
        }, 200);
      }}
      onTouchEnd={(e) => {
        e.preventDefault();
        setIsrecord(false);
        stopRecord();
      }}
      onTouchCancel={(e) => {
        e.preventDefault();
        setIsrecord(false);
        stopRecord();
      }}
    >
      <Popover
        open={isrecord}
        style={{ borderRadius: 10 }}
        content={
          <div className="column" style={{ gap: 12, width: 100 }}>
            <Speaking />
            <span style={{ textAlign: 'center' }}>录制 {time} 秒</span>
            <div
              style={{
                backgroundColor: '#ddd',
                padding: '4px 6px',
                borderRadius: 6,
                marginTop: -6,
              }}
              className="cancle"
            >
              取消
            </div>
          </div>
        }
      >
        <div
          style={{
            width: 36,
            height: 36,
            userSelect: 'none',
            background: `url(${require('@/assets/voice.svg')}) no-repeat center`,
            backgroundSize: 'contain',
          }}
        ></div>
      </Popover>
    </div>
  );
}

export default Recorder;
